package com.guavamail.smtp.command;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;

import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;

import org.apache.mina.core.session.IoSession;

import com.guavamail.smtp.SMTPConnectionHandler;

public abstract class AbstractCommand implements Command {
	public static final String RT = "\r\n";

	private String name;

	public AbstractCommand(String name, String help) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	protected static void getTokenizedString(StringBuilder sb, Collection<String> items, String delim) {
		for (Iterator<String> it = items.iterator(); it.hasNext();) {
			sb.append(it.next());
			if (it.hasNext())
				sb.append(delim);
		}
	}

	protected String[] getArgs(String commandString) {
		List<String> strings = new ArrayList<String>();
		StringTokenizer st = new StringTokenizer(commandString);

		while (st.hasMoreTokens())
			strings.add(st.nextToken());

		return strings.toArray(new String[strings.size()]);
	}

	protected String getArgPredicate(String commandString) {
		if (commandString == null || commandString.length() < 4)
			return "";

		return commandString.substring(4).trim();
	}

	protected String extractEmailAddress(String args, int subcommandOffset) {
		String address = args.substring(subcommandOffset).trim();
		if (address.indexOf('<') == 0)
			address = address.substring(1, address.indexOf('>'));

		return address;
	}

	protected boolean isValidEmailAddress(String address) {
		// MAIL FROM: <>
		if (address.length() == 0)
			return true;

		try {
			InternetAddress[] ia = InternetAddress.parse(address, true);
			return (ia.length != 0);
		} catch (AddressException ae) {
			return false;
		}
	}

	protected void sendResponse(IoSession session, String response) throws IOException {
		SMTPConnectionHandler.sendResponse(session, response);
	}

}
